<?php
namespace backend\models;

use yii\base\Model;
use app\models\Adminuser;

/**
 * Signup form
 */
class SignupForm extends Model
{
    public $username;
    public $email;
    public $password;
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['username', 'trim'],
            ['username', 'required','message' => '请输入用户名'],
            ['username', 'unique', 'targetClass' => 'app\models\Adminuser', 'message' => '用户名已存在'],
            ['username', 'string', 'min' => 2, 'max' => 255],

            ['email', 'trim'],
            ['email', 'required','message' => '请输入正确的邮箱'],
            ['email', 'email'],
            ['email', 'string', 'max' => 255],
            ['email', 'unique', 'targetClass' => 'app\models\Adminuser', 'message' => '该邮箱已经被使用了!!'],

            ['password', 'required','message' => '请输入密码,最少6位'],
            ['password', 'string', 'min' => 6],
        ];
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function signup()
    {
        if (!$this->validate()) {
            return null;
        }
        $user = new AdminUser();
        $user->username = $this->username;
        $user->email = $this->email;
        $user->created_at = strtotime('now');
        $user->updated_at = strtotime('now');
        $user->setPassword($this->password);
        $user->generateAuthKey();

        return $user->save() ? $user : null;


        // 尝试从缓存中取回 $data 
        $data = $cache->get($key);

        if ($data === false) {

        // $data 在缓存中没有找到，则重新计算它的值
        // 将 $data 存放到缓存供下次使用
            $cache->set($key, $data);
        }
    }

    public function update($data = "",$id="")
    {
        $user = new AdminUser();

        $user1 = $user::findone($id);

        $user->username = $data["Adminuser"]['username'];
        $user->email = $data['Adminuser']['email'];
        $user->updated_at = strtotime('now');
        $user->setPassword($data['passowrd']);
        $user->generateAuthKey();

        $user1->username = $data["Adminuser"]['username'];
        $user1->email = $data['Adminuser']['email'];
        $user1->updated_at = strtotime('now');
        $user1->password_hash = $user->password_hash;
        $user1->auth_key = $user->auth_key;
        return $user1->save() ? $user : null;

        // 尝试从缓存中取回 $data
        $data = $cache->get($key);

        if ($data === false) {

            // $data 在缓存中没有找到，则重新计算它的值
            // 将 $data 存放到缓存供下次使用
            $cache->set($key, $data);
        }
    }
}
